//
//  ST_ReceiveCommentsViewController.swift
//  btvideo
//
//  Created by mac on 2020/5/26.
//  Copyright © 2020 JarvanZhang. All rights reserved.
//

import UIKit
import SwifterSwift
import SnapKit
import SDWebImage
import MJRefresh
import HandyJSON
import SwiftyJSON
import SwiftyUserDefaults

class ST_ReceiveCommentsViewController: ST_BTLightBarViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        title_nav_btn.setTitleForAllStates("收到评论")
        
        view.backgroundColor = Color.white
        
        view.addSubview(collectionView)
        collectionView.snp.makeConstraints { (make) in
            make.top.equalTo(own_navigation_bar.snp.bottom)
            make.bottom.right.left.equalToSuperview()
        }
        
        collectionView.mj_header = MJRefreshNormalHeader.init(refreshingBlock: {[weak self] in
            self?.currentPage = 0
            self?.request_data()
        })
        
        
        
        view.addSubview(comment_input_mask_view)
        comment_input_mask_view.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        
        view.addSubview(comment_input_bar)
        comment_input_bar.snp.makeConstraints { (make) in
            make.height.equalTo(ST_CommentInputBar.height)
            make.bottom.left.right.equalToSuperview()
        }
        
        self.request_data()
        
    }
    
    fileprivate var currentPage = 0
    
    fileprivate func request_data(){
        
        currentPage += 1
        
        let param = ["page":currentPage,
                    "size":20] as [String : Any]

        JVrequest(PH.getReceiveCommentListApi,parameters: param, success: { (json) in

            print("打印看看 评论:",json["data"])
            
            var count = 0
            
            let list = json["data"].arrayValue.map { (item) -> ST_ReceiveCommentsCellModel in
                return ST_ReceiveCommentsCellModel.init(fromJson: item)
            }
            
            if self.currentPage == 1{
                self.data_array = list
            }else{
                self.data_array += list
            }
            count = list.count
            
            self.collectionView.reloadData()
            
            self.load_more_option_style(tableView: self.collectionView, count: count, pageSize: 20) {
                
                self.collectionView.mj_footer = MJRefreshAutoNormalFooter.init(refreshingBlock: {[weak self] in

                    self?.request_data()
                })
            }
            
            self.collectionView.mj_header?.endRefreshing()
            self.collectionView.mj_footer?.endRefreshing()

        }) { (code, error) in

            ToastHud(text: error, view: self.view)

            self.collectionView.mj_header?.endRefreshing()
            self.collectionView.mj_footer?.endRefreshing()
        }
    }
    
//    MARK: - Properties
    
    lazy var collectionView: UICollectionView = {
        
        let layout = UICollectionViewFlowLayout()
        
//        layout.headerReferenceSize = CGSize.init(width: ScreenWidth, height: 65)
        
        layout.minimumLineSpacing = 0
        //        layout.minimumInteritemSpacing = 14
        
        let bottomEdge = iPhoneXSeries ? BTSafeAreaBottom + 30 : 20 + 20
        
//        layout.sectionInset = UIEdgeInsets.init(top: 0, left: 15, bottom: bottomEdge, right: 0)
        
        let collection = UICollectionView(frame: .zero, collectionViewLayout: layout)
        
        collection.contentInset = UIEdgeInsets.init(top: 0, left: 0, bottom: bottomEdge, right: 0)
        
        collection.register(cellWithClass: ReceiveCommentsCell.self)
        
        collection.delegate = self
        
        collection.dataSource = self
        
        collection.alwaysBounceVertical = true
        
        collection.backgroundColor = Color.white
        
        if #available(iOS 11.0, *) {
            collection.contentInsetAdjustmentBehavior = .never
        }
        return collection
    }()
    
    fileprivate var data_array = [ST_ReceiveCommentsCellModel]()

    
    fileprivate lazy var comment_input_bar:ST_CommentInputBar = {
       let control = ST_CommentInputBar()
        control.endEditClosure = {[weak self] str,replyId,commentId in
            self?.end_edit_comment_handle()
            self?.send_message_handle(comment: str, replyUserId: replyId, commentId: commentId)
        }
        control.keyBroadHiddenClosure = {[weak self]  in
            self?.hidden_mask_view(hidden: true)
        }
        control.keyBroadShowClosure = {[weak self]  in
            self?.hidden_mask_view(hidden: false)
        }
        return control
    }()
    
    fileprivate lazy var comment_input_mask_view:UIView = {
       let control = UIView()
        control.alpha = 0
        control.backgroundColor = UIColor.init(white: 0, alpha: 0.3)
        let tap = UITapGestureRecognizer.init(target: self, action: #selector(end_edit_comment_handle))
        control.addGestureRecognizer(tap)
        return control
    }()
    
}

extension ST_ReceiveCommentsViewController:UICollectionViewDataSource,UICollectionViewDelegateFlowLayout{
    
    
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return data_array.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        
        let cell = collectionView.dequeueReusableCell(withClass: ReceiveCommentsCell.self, for: indexPath)
        
        let cellModel = self.data_array[indexPath.item]
        
        cell.model = cellModel
        
        return cell
    }
    
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        
        let size = CGSize.init(width: ScreenWidth, height: self.data_array[indexPath.item].cellHeight)
        
        return size
    }
    
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        guard let model = data_array[safe:indexPath.row] else { return }
        
        let vc = ST_BTSheetActionController.init(title: nil, message: nil)
        
        let attr: [NSAttributedString.Key : Any] = [.font: UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.medium),.foregroundColor: UIColor(red: 0.2, green: 0.2, blue: 0.2, alpha: 1)]
        
        let str2 = NSMutableAttributedString.init(string: "回复")
        
        str2.addAttributes(attr, range: NSRange(location: 0, length: str2.length))
        
        vc.addAction(ST_BTAlertAction.init(title: str2, handler: {[weak self] (action) in
                
            guard let strongSelf = self else{return}
            
            strongSelf.comment_input_bar.receiveCommentModel = model
            
//            日常可以 回复 任意
            if model.daily_content_id > 0{
                strongSelf.comment_input_bar.determinFace = false
                strongSelf.comment_input_bar.onlyInputEmoji = false
            }
            else if FACE_AVATAE_STATE != 3{
                strongSelf.comment_input_bar.determinFace = true
                strongSelf.comment_input_bar.onlyInputEmoji = true
            }else{
                strongSelf.comment_input_bar.determinFace = false
                strongSelf.comment_input_bar.onlyInputEmoji = false
            }
            
            let nickname = model.nickname
            
            strongSelf.comment_input_bar.startEdit(replyUserId: model.commentMemberId.string, commentId: model.commentId.string, nickName: nickname)
        }))
        
        
        let str3 = NSMutableAttributedString.init(string: "查看" + model.title_name)
        
        str3.addAttributes(attr, range: NSRange(location: 0, length: str3.length))
        
        vc.addAction(ST_BTAlertAction.init(title: str3, handler: { (action) in
           
//            日常评论
            if model.daily_content_id > 0{
                
                let vc = ST_DaliyMomentDetailController()
               
                vc.dailyId = model.daily_content_id.string
               
               vc.userId = model.own_member_accid
               
               self.navigationController?.pushViewController(vc)
            }
//            特质评论
            else{
                self.push_pec_handle(model: model)
            }
        }))
        
        let str4 = NSMutableAttributedString.init(string: "删除评论")
        
        str4.addAttributes(attr, range: NSRange(location: 0, length: str4.length))
        
        vc.addAction(ST_BTAlertAction.init(title: str4, handler: {[weak self] (action) in
            
            
            self?.data_array.remove(at: indexPath.row)
            
               self?.collectionView.performBatchUpdates({
                   self?.collectionView.deleteItems(at:[indexPath])
               }, completion:nil)
            
            JVrequest(PH.deleteCommentApi,parameters: ["comment_id":model.commentId], success: { (json) in
            
                print("调试 使用 删除 评论 Finish")
                
            }) { (code, err) in
                
                print("调试 使用 删除 评论:",err)
            }
            
            
        }))
        
        vc.show()
        
        
        
    }
    
    
    
    fileprivate func push_pec_handle(model:ST_ReceiveCommentsCellModel){
        
        let vc = ST_PeculiarityGroupViewController.init(accid: model.own_member_accid, groupId: model.groupId.string, peculiarity_id: model.featureId.string, firstPhotoSize: CGSize.init(width: model.width.cgFloat, height: model.height.cgFloat), remark: "")
        
        let nav = PairsCenterInteractiveNavigationController.init(rootViewController: vc)
        
        nav.overCurrentContext = true
        
        GlobalPresent(toController: nav, animated: true)
    }
    
    func hidden_mask_view(hidden:Bool){

        UIView.animate(withDuration: 0.25, animations: {
            
            self.comment_input_mask_view.alpha = hidden ? 0 : 1
            
        }) { (f) in
            
        }
        
    }
    
    @objc fileprivate func end_edit_comment_handle(){
        
        comment_input_bar.endEditing(true)
        
        
    }
    
    
    func send_message_handle(comment:String,replyUserId:String?,commentId:String?){
        
        if BTVerticalAlertViewController.toastBindPhoneRequireAlert(fromController: self) {
            return
        }
        
        guard let model = self.comment_input_bar.receiveCommentModel else { return  }
        
        var api = PH.sendCommentApi
        if model.daily_content_id < 1{
            //        只能发表情，但是没有检测到表情
            if model.type == 2 && comment.containEmoji == false{
                
                self.toast(text: "该特质只支持emoji评论")
                
                return
            }
            
            
             if let id = replyUserId{
    //            收到的评论页｜个人特质页
                ST_BTGlobalDataCenter.shared.reply_peculiarity_comment_event(peculiarity_id: model.groupId.string, reply_user_id: id, source: "收到的评论页", is_own_peculiarity: model.own_member_accid == Defaults[.currentUserID])
                
            }else{
                
                ST_BTGlobalDataCenter.shared.commentPeculiarityEvent(peculiarity_id: model.groupId.string, commented_user_id: model.own_member_accid)
                
            }
            
        }else{
            
            api = PH.commentDailyApi
            
            if let id = replyUserId{
                
//                收到的评论页｜个人日常页
                ST_BTGlobalDataCenter.shared.replyDailyCommentEvent(daily_id: model.daily_content_id.string, reply_user_id: id, dailyType: model.featureName, source: "收到的评论页", isMyDaily: model.own_member_accid == Defaults[.currentUserID])
                
            }else{
                
                ST_BTGlobalDataCenter.shared.commentDailyEvent(dailyType: model.featureName, daily_id: model.daily_content_id.string, commented_user_id: model.own_member_accid)
                
            }
            
            
        }
        
        var param = ["target_accid":model.accid,"feature_id":model.featureId,"group_id":model.groupId,"type":model.type,"comment":comment,"daily_content_id":model.daily_content_id] as [String : Any]
        
        
        if let id = commentId{
            param.updateValue(id, forKey: "target_comment_id")
        }
        if let id = replyUserId{
            param.updateValue(id, forKey: "target_member_id")
        }
        
        JVrequest(api,parameters: param, success: { (json) in
            
            self.currentPage = 0

            self.request_data()
            
        }) { (code, err) in
            self.toast(text: err)
        }
        
    }
    
    
}


//MARK: - Cell
fileprivate class ReceiveCommentsCell: UICollectionViewCell {
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        contentView.backgroundColor = .white
        
        contentView.addSubview(avatar_image_view)
        avatar_image_view.snp.makeConstraints { (make) in
            make.width.height.equalTo(46)
            make.left.equalToSuperview().offset(15)
            make.top.equalToSuperview().offset(17)
        }
        
        contentView.addSubview(nickname_label)
        nickname_label.snp.makeConstraints { (make) in
            make.height.equalTo(22)
            make.left.equalToSuperview().offset(71)
            make.top.equalTo(avatar_image_view).offset(2)
            
            if ScreenWidth < 380{
                make.width.lessThanOrEqualTo(100)
            }else{
                make.width.lessThanOrEqualTo(140)
            }
        }
        
        
        
        
        contentView.addSubview(cover_image_view)
        cover_image_view.snp.makeConstraints { (make) in
            make.width.height.equalTo(50)
            make.right.equalToSuperview().offset(-15)
            make.top.equalToSuperview().offset(15)
        }
        
        
        contentView.addSubview(sub_title_label)
        sub_title_label.snp.makeConstraints { (make) in
            make.left.equalTo(nickname_label)
            make.top.equalTo(nickname_label.snp.bottom).offset(3)
            make.height.equalTo(17)
        }
        
        contentView.addSubview(content_label)
        content_label.snp.makeConstraints { (make) in
            make.bottom.equalToSuperview().offset(-15)
            make.left.equalTo(nickname_label)
            make.right.equalToSuperview().offset(-15)
        }
        
        
        contentView.addSubview(sign_image_container)
        sign_image_container.snp.makeConstraints { (make) in
            make.left.equalTo(nickname_label.snp.right).offset(4)
            make.centerY.equalTo(nickname_label).offset(-1)
        }
        
        contentView.addSubview(time_label)
        
        time_label.snp.makeConstraints { (make) in
            
            make.left.equalTo(sign_image_container.snp.right).offset(5)
//            40 + 4 + 5 或者 5
            make.centerY.equalTo(nickname_label)
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
//    MARK: - properties
    fileprivate lazy var avatar_image_view:UIImageView = {
       let control = UIImageView()
        control.contentMode = .scaleAspectFill
        control.cornerRadius = 46/2.0
        let tap = UITapGestureRecognizer.init(target: self, action: #selector(push_user_center_handle))
        control.isUserInteractionEnabled = true
        control.addGestureRecognizer(tap)
        return control
    }()
    
    fileprivate lazy var nickname_label:UILabel = {
        let control = UILabel.init()
        control.textColor = Color.init(hexString: "#333333")
        control.font = UIFont.systemFont(ofSize: 16, weight: UIFont.Weight.semibold)
        return control
    }()
    
    fileprivate lazy var time_label:UILabel = {
        let control = UILabel.init()
        control.textColor = Color.init(hexString: "#ACB4C0")
        control.font = UIFont.systemFont(ofSize: 12, weight: UIFont.Weight.regular)
        return control
    }()
    
    fileprivate lazy var cover_image_view:UIImageView = {
       let control = UIImageView()
        control.contentMode = .scaleAspectFill
        control.cornerRadius = 13
        
        let tap = UITapGestureRecognizer.init(target: self, action: #selector(pushPecGroupHandle))
        control.isUserInteractionEnabled = true
        control.addGestureRecognizer(tap)
        return control
    }()
    
    
    fileprivate lazy var sub_title_label:UILabel = {
        let control = UILabel.init()
        control.textColor = Color.init(hexString: "#ACB4C0")
        control.font = UIFont.systemFont(ofSize: 12, weight: UIFont.Weight.regular)
        
        return control
    }()
    
    fileprivate lazy var content_label:UILabel = {
        let control = UILabel.init()
        control.numberOfLines = 0
        return control
    }()
    
    
    fileprivate lazy var sign_image_container:UIImageView = {
        let control = UIImageView()
        return control
    }()
    
    
    var model = ST_ReceiveCommentsCellModel.init(fromJson: JSON.null){
        didSet{
            
       
            
            avatar_image_view.pin_setImage(from: model.avatar.compress_small_image(width: 37*3).url, placeholderImage: ST_SwiftConst.shared.fetch_random_place_holder_image())
            
            
            if model.content.count > 2{
                
                cover_image_view.pin_setImage(from: model.content.compress_small_image(width: 37*3).url, placeholderImage: ST_SwiftConst.shared.fetch_random_place_holder_image())
                
                cover_image_view.isHidden = false
                
            }else{
                
                cover_image_view.isHidden = true
            }
            
            
            
          
            nickname_label.text = model.nickname
            
            time_label.text = model.createTime.double.b_t_global_date_string()
            
            content_label.attributedText = model.commentAttr
            
            sub_title_label.text = model.subText
            
            
            
            if CHECK_MEMBER_STATUS(expirationTime: model.vip_expire) == .subscribe{
                sign_image_container.image = SC.YYMemberSignImage
            }else if model.face_audit_state == 3{
                sign_image_container.image = SC.YYFaceSignImage
            }else{
                sign_image_container.image = nil
            }
            
        
        }
    }
    
    
    @objc fileprivate func push_user_center_handle(){
        
        
        let vc = ST_PairsCenterViewController()
        
        vc.accid = self.model.accid

        let nav = PairsCenterInteractiveNavigationController.init(rootViewController: vc)
        
        nav.overCurrentContext = true
        
        GlobalPresent(toController: nav)
        
    }
    
}
extension ReceiveCommentsCell{
    
    @objc fileprivate func pushPecGroupHandle(){
        
        
//        日常评论
       if model.daily_content_id > 0{
                       
           let vc = ST_DaliyMomentDetailController()
          
           vc.dailyId = model.daily_content_id.string
          
           vc.userId = model.own_member_accid
          
           self.parentViewController?.navigationController?.pushViewController(vc)
       }
//            特质评论
       else{
                    
            let vc = ST_PeculiarityGroupViewController.init(accid: model.own_member_accid, groupId: model.groupId.string, peculiarity_id: model.featureId.string, firstPhotoSize: CGSize.init(width: model.width.cgFloat, height: model.height.cgFloat), remark: "")
            
            let nav = PairsCenterInteractiveNavigationController.init(rootViewController: vc)
            
            nav.overCurrentContext = true
            
            GlobalPresent(toController: nav, animated: true)
       }
        
        
        
        
    }
}




